package com.imooc.Interceptor;

import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 用户拦截器
 */
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 访问controller之前进行拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从前端的header里面获取userId和userToken
        String userId = request.getParameter("userId");
        String userToken = request.getParameter("userToken");
        if (StringUtils.isBlank(userId) && StringUtils.isBlank(userToken)) {
            buildErrorMsg(response, IMOOCJSONResult.errorMsg("用户未登录"));
            return false;
        }
        String USER_TOKEN = "USER";
        String uniqueUserToken = redisOperator.get(USER_TOKEN + ":" + userId);
        // 校验token是否一致
        if (!uniqueUserToken.equals(userToken)) {
            buildErrorMsg(response, IMOOCJSONResult.errorMsg("账号异地登录"));
        }
        // 返回true才能被认为是拦截通过
        return true;
    }

    /**
     * 构建拦截错误信息
     */
    public void buildErrorMsg(HttpServletResponse response, IMOOCJSONResult result) {
        OutputStream outputStream = null;
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json");
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            assert outputStream != null;
            outputStream.write(Objects.requireNonNull(JsonUtils.objectToJson(result)).getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
